package com.quectel.util.servlet.filter;

import com.quectel.util.common.HtmlUtils;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.Map;

/**
 * 防止xss注入过滤器
 */
public class XssFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        XssAndSqlHttpServletRequestWrapper xssRequestWrapper = new XssAndSqlHttpServletRequestWrapper(req);
        chain.doFilter(xssRequestWrapper, response);
    }


    public static class XssAndSqlHttpServletRequestWrapper extends HttpServletRequestWrapper {
        private HttpServletRequest request;

        public XssAndSqlHttpServletRequestWrapper(HttpServletRequest request) {
            super(request);
            this.request = request;
        }

        @Override
        public String getParameter(String name) {
            String value = request.getParameter(name);
            if (!StringUtils.isEmpty(value)) {
                value = HtmlUtils.encode(value);
            }
            return value;
        }

        @Override
        public String[] getParameterValues(String name) {
            String[] parameterValues = super.getParameterValues(name);
            if (parameterValues == null) {
                return null;
            }
            for (int i = 0; i < parameterValues.length; i++) {
                String value = parameterValues[i];
                parameterValues[i] = HtmlUtils.encode(value);
            }
            return parameterValues;
        }

        @Override
        public Map<String, String[]> getParameterMap() {
            if (super.getParameterMap() != null) {
                for (Map.Entry<String, String[]> entry : super.getParameterMap().entrySet()) {
                    if (entry.getValue() != null) {
                        for (int i = 0; i < entry.getValue().length; i++) {
                            if (StringUtils.isNotBlank(entry.getValue()[i])) {
                                entry.getValue()[i] = HtmlUtils.encode(entry.getValue()[i]);
                            }
                        }
                    }
                }
            }
            return super.getParameterMap();
        }
    }
}
